from flask import Flask
import os
import logging
from datetime import datetime, timedelta

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('Personal_Blog_System')

# 导入必要的模块
from flask import Flask, request, g
# 移除JWT导入，使用Flask-Login会话认证

# 创建Flask应用实例
app = Flask(__name__, instance_relative_config=True)

# 导入配置
from config import Config
import os

# 加载单一开发配置
app.config.from_object(Config)

# 移除JWT管理器，使用Flask-Login会话认证

# 导入扩展
from extensions import db, login_manager
from models import User

# 初始化扩展
login_manager.init_app(app)
login_manager.login_view = 'auth.login'
db.init_app(app)

# 请求拦截器 - 请求前处理
@app.before_request
def before_request_handler():
    # 记录请求开始时间
    g.start_time = datetime.now()
    
    # 记录请求信息
    logger.info(f"Request: {request.method} {request.path} - IP: {request.remote_addr}")
    
    # API路径使用Flask-Login会话认证，无需额外验证

# 导入蓝图并注册
from routes import main_bp, auth_bp
from routes.post_api import post_api
from routes.category_api import category_api
from routes.tag_api import tag_api
from routes.comment_api import comment_api
from routes.user_api import user_api
from routes.upload_api import upload_api

app.register_blueprint(main_bp)
app.register_blueprint(auth_bp, url_prefix='/auth')
app.register_blueprint(post_api)
app.register_blueprint(category_api)
app.register_blueprint(tag_api)
app.register_blueprint(comment_api)
app.register_blueprint(user_api)
app.register_blueprint(upload_api)

# 添加静态文件路由，用于访问上传的文件
from flask import send_from_directory
import os

@app.route('/files/<path:filename>')
def uploaded_file(filename):
    """提供上传文件的访问"""
    # 将反斜杠转换为正斜杠，确保跨平台兼容性
    filename = filename.replace('\\', '/')
    
    # 构建文件路径
    file_path = os.path.join(app.root_path, 'files', filename)
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        from flask import abort
        abort(404)
    
    return send_from_directory(os.path.join(app.root_path, 'files'), filename)

# 创建数据库表
with app.app_context():
    from models import User, Post, Category, Tag, Comment, PostTag
    db.create_all()

if __name__ == '__main__':
    app.run(debug=False)
